import requests
from config.Setting import Setting
from request.remote.CharMap import en_check
from autoTask.Base import ThrowError


def add(phone):
    tid = en_check()
    url = f'{Setting.REMOTE_SEVER_API}/code'
    method = 'PUT'
    data = {
        'phone': phone,
        'tid': tid
    }
    try:
        response = requests.request(method, url, data=data)
    except requests.exceptions.ConnectionError:
        raise ThrowError('远程服务器连接超时')
    except Exception:
        raise ThrowError('远程服务器异常')
    if response.status_code == 200:
        return tid
    else:
        raise ThrowError('服务器数据库操作异常')


def get(tid):
    url = f'{Setting.REMOTE_SEVER_API}/code/{tid}'
    method = 'GET'
    try:
        response = requests.request(method, url).json()
    except Exception:
        raise ThrowError('远程服务器异常')
    code = response.get('code')
    return code


if __name__ == '__main__':
    res = add('1')
